package model

import (
	"encoding/json"

	"gorm.io/gorm"
)

func AddReport(db *gorm.DB, c Report) (*Report, error) {
	result := db.Create(&c)
	if result.Error != nil {
		return nil, result.Error
	}
	return &c, nil
}

func DeleteReport(db *gorm.DB, id uint) error {
	result := db.Delete(&Report{}, id)
	return result.Error
}

func ListReport(db *gorm.DB, collection uint) ([]Report, error) {
	var ret []Report
	result := db.Where("collection_id = ?", collection).Find(&ret)
	if result.Error != nil {
		return nil, result.Error
	}
	return ret, nil
}

func UpdateReport(db *gorm.DB, id uint, content json.RawMessage) (*Report, error) {
	var ret Report
	ret.ID = id
	result := db.Model(&ret).Update("content", content)
	if result.Error != nil {
		return nil, result.Error
	}

	result = db.Find(&ret)
	if result.Error != nil {
		return nil, result.Error
	}
	return &ret, nil
}
